package com.fc.test.service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fc.test.mapper.auto.*;
import com.fc.test.model.auto.*;
import com.fc.test.util.DateUtil;
import com.fc.test.util.OrderNOUtil;
import com.fc.test.util.RedPackageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.fc.test.common.base.BaseService;
import com.fc.test.common.support.Convert;
import com.fc.test.model.custom.Tablepar;
import com.fc.test.util.SnowflakeIdWorker;
import org.springframework.transaction.annotation.Transactional;

/**
 * Service
* @Title: TAbbBiamminService.java 
* @Package com.fc.test.entity 
* @author fuce
* @email 87766867@qq.com
* @date 2019-08-19 15:25:48  
 */
@Service
public class TAbbBiamminService implements BaseService<TAbbBiammin, TAbbBiamminExample>{
	@Autowired
	private TAbbBiamminMapper tAbbBiamminMapper;

	@Autowired
	private TAbbBmliuyanMapper bmliuyanMapper;

	@Autowired
	private TAbbMemberMapper memberMapper;

	@Autowired
	private TAbbOrderMapper orderMapper;

	@Autowired
	private TAbbCommissionMapper commissionMapper;
	@Autowired
	private TAbbCommissionMapper tAbbCommissionMapper;
	/**
	 * 分页查询
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	 public PageInfo<TAbbBiammin> list(Tablepar tablepar,String name){
	        TAbbBiamminExample testExample=new TAbbBiamminExample();
	        testExample.setOrderByClause("id ASC");
		    TAbbBiamminExample.Criteria criteria=testExample.createCriteria();
	        if(name!=null&&!"".equals(name)){
				criteria.andTitleLike("%"+name+"%");
			}
		 TAbbBiamminExample.Criteria criteria1=testExample.createCriteria();
		 criteria1.andTypeEqualTo(1);
		 criteria1.andYuliu2EqualTo("1");
		 testExample.or(criteria1);
		 PageHelper.startPage(tablepar.getPageNum(), tablepar.getPageSize());
		 List<TAbbBiammin> list= tAbbBiamminMapper.selectByExample(testExample);
	        PageInfo<TAbbBiammin> pageInfo = new PageInfo<TAbbBiammin>(list);
	        return  pageInfo;
	 }

	@Override
	public int deleteByPrimaryKey(String ids) {
		List<String> lista=Convert.toListStrArray(ids);
		for (String id:lista){
			TAbbOrderExample example=new TAbbOrderExample();
			TAbbOrderExample.Criteria criteria=example.createCriteria();
			criteria.andObjidEqualTo(id);
			criteria.andTypeEqualTo(4);
			List<TAbbOrder> orderList=orderMapper.selectByExample(example);
			if (orderList!=null && orderList.size()>0){
				for (TAbbOrder tAbbOrder:orderList){
					if (tAbbOrder.getRenwumoney()>0){
						//返回任务余额到用户账号
						TAbbMember tAbbMember=memberMapper.selectByPrimaryKey(tAbbOrder.getUserid());
						TAbbMember tAbbMember3=new TAbbMember();
						tAbbMember3.setId(tAbbMember.getId());
						tAbbMember3.setAccount(tAbbMember.getAccount()+tAbbOrder.getRenwumoney());
						memberMapper.updateByPrimaryKey(tAbbMember3);

						//返回任务余额到用户账号的记录
						TAbbCommission tAbbCommission3=new TAbbCommission();
						tAbbCommission3.setCreattime(DateUtil.getCurrentDateTimeStr());
						tAbbCommission3.setType(1);
						tAbbCommission3.setBeiyongone(String.valueOf(tAbbOrder.getRenwumoney()));
						tAbbCommission3.setBusinessid("3");
						tAbbCommission3.setMemberid(tAbbMember.getId());
						tAbbCommission3.setMessage("消除任务");
						tAbbCommission3.setId(SnowflakeIdWorker.getUUID());
						tAbbCommissionMapper.insertSelective(tAbbCommission3);
					}
				}
			}
		}
		TAbbBiamminExample example=new TAbbBiamminExample();
		example.createCriteria().andIdIn(lista);
		return tAbbBiamminMapper.deleteByExample(example);
	}


	@Override
	public TAbbBiammin selectByPrimaryKey(String id) {

		return tAbbBiamminMapper.selectByPrimaryKey(id);
	}


	@Override
	public int updateByPrimaryKeySelective(TAbbBiammin record) {
		return tAbbBiamminMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 添加
	 */
	@Override
	public int insertSelective(TAbbBiammin record) {
		//添加雪花主键id
		record.setId(SnowflakeIdWorker.getUUID());
		return tAbbBiamminMapper.insertSelective(record);
	}










	@Override
	public int updateByExampleSelective(TAbbBiammin record, TAbbBiamminExample example) {

		return tAbbBiamminMapper.updateByExampleSelective(record, example);
	}


	@Override
	public int updateByExample(TAbbBiammin record, TAbbBiamminExample example) {

		return tAbbBiamminMapper.updateByExample(record, example);
	}

	@Override
	public List<TAbbBiammin> selectByExample(TAbbBiamminExample example) {

		return tAbbBiamminMapper.selectByExample(example);
	}


	@Override
	public long countByExample(TAbbBiamminExample example) {

		return tAbbBiamminMapper.countByExample(example);
	}


	@Override
	public int deleteByExample(TAbbBiamminExample example) {

		return tAbbBiamminMapper.deleteByExample(example);
	}

	public List<TAbbBiammin> getBianminByPage(int page,int type,String category,String memberId){
		Map<String,Object> resMap = new HashMap<>();
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("page",page);
		paramMap.put("type",type);
		paramMap.put("category",category);
		List<TAbbBiammin> list = tAbbBiamminMapper.getBianminByPage(paramMap);
		for(TAbbBiammin bianmin:list){
			if(type==1){
				bianmin.setIsReceive(0);
			}else if(type==2){
				Map<String,Object> map = new HashMap<>();
				map.put("memberId",memberId);
				map.put("bmid",bianmin.getId());
				int count = commissionMapper.getTodayBmTimes(map);
				if(count>0){
					bianmin.setIsReceive(1);
				}else{
					bianmin.setIsReceive(0);
				}
			}
		}
		return list;
	}


	@Transactional
	public Map<String,Object> releaseBianmin(TAbbBiammin tAbbBiammin){
		Map<String,Object> resMap = new HashMap<>();
		TAbbMember member = memberMapper.selectByPrimaryKey(tAbbBiammin.getUserid());
		int isVip = member.getIsvip();
		double price = 0d;
		if(null!=tAbbBiammin.getPrice()){
			price = tAbbBiammin.getPrice();
		}
		if(price>0 && price<2.5){
			resMap.put("success",false);
			resMap.put("msg","红包总金额需大于2.5元");
		}else{
			tAbbBiammin.setId(SnowflakeIdWorker.getUUID());
			tAbbBiammin.setCreattime(DateUtil.getCurrentDateTimeStr());
			tAbbBiammin.setUsername(member.getNicename());
			tAbbBiammin.setBalance(price);
			if(price>0){
				tAbbBiammin.setType(2);
				tAbbBiammin.setYuliu2(DateUtil.getCurrentDateTimeStr());
				tAbbBiammin.setYuliu1("50");
			}else{
				tAbbBiammin.setType(1);
			}
			tAbbBiammin.setYuliu3("0");


			//根据置顶次数计算置顶费用
			int leftZhidingNum = member.getZhidingnum();
			int zhiidingNum = 0;
			if(null!=tAbbBiammin.getDays()){
				zhiidingNum = tAbbBiammin.getDays();
			}
			double zhidingMoney = 0d;
			if(leftZhidingNum>0&&leftZhidingNum>=zhiidingNum){
				//如果使用了免费次数则减去
//				member.setZhidingnum(leftZhidingNum-zhiidingNum);
				zhidingMoney = 0d;
				leftZhidingNum -=zhiidingNum;
			}else{
				if(leftZhidingNum>0){
//					member.setZhidingnum(0);
					zhidingMoney = zhiidingNum-leftZhidingNum;
				}else{
					zhidingMoney = zhiidingNum;
				}
				leftZhidingNum=0;
			}

			//根据是否会员判断用不用付任务费
			double renwuMoney = 0d;
			if(isVip>0){//vip免费发
				renwuMoney = 0d;
			}else{
				int count = tAbbBiamminMapper.get7DayTimes(tAbbBiammin.getUserid());
				if(count>0){//普通会员一周内第一次发免费，其余一次一元
					renwuMoney = 1d;
				}else{
					renwuMoney = 0d;
				}
			}

			//计算订单总金额
			double totalMoney = zhidingMoney+renwuMoney+price;
			DecimalFormat df = new DecimalFormat("#.00");
			totalMoney = Double.parseDouble(df.format(totalMoney));
			if(totalMoney>0){
				TAbbOrder order = new TAbbOrder();
				order.setId(SnowflakeIdWorker.getUUID());
				order.setCreatetime(DateUtil.getCurrentDateTimeStr());
				order.setType(2);
				order.setUserid(tAbbBiammin.getUserid());
				order.setOrderno(OrderNOUtil.getOrderNoByTime());
				order.setObjid(tAbbBiammin.getId());
				//红包金额
				order.setHongbaomoney(price);
				//置顶金额
				order.setGoodsmoney(zhidingMoney);
				//便民信息vip会员免费，普通会员一条一元
				order.setRenwumoney(renwuMoney);
				order.setPaymoney(totalMoney);
				order.setPaystatus(0);
				order.setYuliu3(tAbbBiammin.getTitle());
				order.setYuliu4(member.getNicename());
				orderMapper.insert(order);
				resMap.put("orderid",order.getId());
			}else{
				tAbbBiammin.setYuliu3("1");
				resMap.put("orderid","");

				//减去会员的置顶次数
				member.setZhidingnum(leftZhidingNum);
				memberMapper.updateByPrimaryKey(member);
			}
//			memberMapper.updateByPrimaryKey(member);
			int flag = tAbbBiamminMapper.insert(tAbbBiammin);
			if(flag>0){
				resMap.put("success",true);
				resMap.put("msg","发布成功");
			}else{
				resMap.put("success",false);
				resMap.put("msg","发布失败");
			}
		}
		return resMap;
	}

	@Transactional
	public Map<String,Object> getBianinDetail(String id,String userid){
		Map<String,Object> resMap = new HashMap<>();
		TAbbBiammin tAbbBiammin = tAbbBiamminMapper.selectByPrimaryKey(id);
		int type = tAbbBiammin.getType();
		if(2==type&&tAbbBiammin.getBalance()>0){
			//查询用户今天是否已经领过红包
			Map<String,Object> paramMap = new HashMap<>();
			paramMap.put("memberId",userid);
			paramMap.put("bmid",id);
			int count = commissionMapper.getTodayBmTimes(paramMap);
			if(count==0){//今天没有领过红包
				/*//本条便民信息剩余的红包金额
				double balance = tAbbBiammin.getBalance();
				//本条便民信息剩余的红包个数
				String leftNum = tAbbBiammin.getYuliu1();

				//获得本次红包金额
				double redPcket = RedPackageUtil.doIt(balance,Integer.parseInt(leftNum));
				DecimalFormat df = new DecimalFormat("#.00");
				redPcket = Double.parseDouble(df.format(redPcket));
				balance = Double.parseDouble(df.format(balance-redPcket));
				leftNum = String.valueOf(Integer.parseInt(leftNum)-1);
				tAbbBiammin.setBalance(balance);
				tAbbBiammin.setYuliu1(leftNum);
				if(Integer.parseInt(leftNum)==0){//红包发完变成普通便民信息
					tAbbBiammin.setType(1);
				}
				tAbbBiamminMapper.updateByPrimaryKey(tAbbBiammin);

				//给用户钱包加上红包金额--------------------------------------------------
				TAbbMember member = memberMapper.selectByPrimaryKey(userid);
				member.setAccount(member.getAccount()+redPcket);
				memberMapper.updateByPrimaryKey(member);

				//加流水-------------------------------------------------------------------
				TAbbCommission commission = new TAbbCommission();
				commission.setId(SnowflakeIdWorker.getUUID());
				commission.setType(1);
				commission.setBusinessid("1");
				commission.setMemberid(userid);
				commission.setBeiyongtwo(id);
				commission.setBeiyongone(redPcket+"");
				commission.setCreattime(DateUtil.getCurrentDateTimeStr());
				commission.setMessage("任务奖励");
				tAbbCommissionMapper.insert(commission);

				resMap.put("redPcket",redPcket);*/
				tAbbBiammin.setIsReceive(0);
			}else{
				tAbbBiammin.setIsReceive(1);
			}
		}else{
			tAbbBiammin.setIsReceive(1);
		}
		resMap.put("success",true);
		resMap.put("msg","获取便民信息详情成功");
		resMap.put("data",tAbbBiammin);
		return resMap;
	}

	@Transactional
	public Map<String,Object> getBianminRedPcket(String id,String userid){
		Map<String,Object> resMap = new HashMap<>();
		resMap.put("redPcket","");
		TAbbBiammin tAbbBiammin = tAbbBiamminMapper.selectByPrimaryKey(id);
		int type = tAbbBiammin.getType();
		if(2==type){
			//查询用户今天是否已经领过红包
			Map<String,Object> paramMap = new HashMap<>();
			paramMap.put("memberId",userid);
			paramMap.put("bmid",id);
			int count = commissionMapper.getTodayBmTimes(paramMap);
			if(count==0){//今天没有领过红包
				//本条便民信息剩余的红包金额
				double balance = tAbbBiammin.getBalance();
				//本条便民信息剩余的红包个数
				String leftNum = tAbbBiammin.getYuliu1();

				//获得本次红包金额
				double redPcket = RedPackageUtil.doIt(balance,Integer.parseInt(leftNum));
				DecimalFormat df = new DecimalFormat("#.00");
				redPcket = Double.parseDouble(df.format(redPcket));
				balance = Double.parseDouble(df.format(balance-redPcket));
				leftNum = String.valueOf(Integer.parseInt(leftNum)-1);
				tAbbBiammin.setBalance(balance);
				tAbbBiammin.setYuliu1(leftNum);
				if(Integer.parseInt(leftNum)==0){//红包发完变成普通便民信息
					tAbbBiammin.setType(1);
				}
				tAbbBiamminMapper.updateByPrimaryKey(tAbbBiammin);

				//给用户钱包加上红包金额--------------------------------------------------
				TAbbMember member = memberMapper.selectByPrimaryKey(userid);
				member.setAccount(member.getAccount()+redPcket);
				memberMapper.updateByPrimaryKey(member);

				//加流水-------------------------------------------------------------------
				TAbbCommission commission = new TAbbCommission();
				commission.setId(SnowflakeIdWorker.getUUID());
				commission.setType(1);
				commission.setBusinessid("1");
				commission.setMemberid(userid);
				commission.setBeiyongtwo(id);
				commission.setBeiyongone(redPcket+"");
				commission.setCreattime(DateUtil.getCurrentDateTimeStr());
				commission.setMessage("任务奖励");
				tAbbCommissionMapper.insert(commission);

				resMap.put("redPcket",redPcket);
			}
		}
		resMap.put("success",true);
		resMap.put("msg","获取便民红包成功");
		return resMap;
	}

	public int addPinglun(String bmid,String userid,String content){
		TAbbMember member = memberMapper.selectByPrimaryKey(userid);
		TAbbBmliuyan tAbbBmliuyan = new TAbbBmliuyan();
		tAbbBmliuyan.setId(SnowflakeIdWorker.getUUID());
		tAbbBmliuyan.setCreatetime(DateUtil.getCurrentDateTimeStr());
		tAbbBmliuyan.setBmid(bmid);
		tAbbBmliuyan.setType(1);
		tAbbBmliuyan.setContent(content);
		tAbbBmliuyan.setUserid(userid);
		tAbbBmliuyan.setUsername(member.getNicename());

		return bmliuyanMapper.insert(tAbbBmliuyan);
	}

	public int addHuifu(String lyid,String userid,String content){

		TAbbMember member = memberMapper.selectByPrimaryKey(userid);
		TAbbBmliuyan liuyan = bmliuyanMapper.selectByPrimaryKey(lyid);

		TAbbBmliuyan tAbbBmliuyan = new TAbbBmliuyan();
		tAbbBmliuyan.setId(SnowflakeIdWorker.getUUID());
		tAbbBmliuyan.setCreatetime(DateUtil.getCurrentDateTimeStr());
		tAbbBmliuyan.setBmid(liuyan.getBmid());
		tAbbBmliuyan.setType(2);
		tAbbBmliuyan.setContent(content);
		tAbbBmliuyan.setUserid(userid);
		tAbbBmliuyan.setUsername(member.getNicename());
		tAbbBmliuyan.setLyid(lyid);
		tAbbBmliuyan.setReusername(liuyan.getUsername());

		return bmliuyanMapper.insert(tAbbBmliuyan);
	}

	public List<Map<String,Object>> getLiuyanList(String bmid,int page){
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("bmid",bmid);
		paramMap.put("page",page);
		List<TAbbBmliuyan> list = bmliuyanMapper.getLiuyanList(paramMap);
		List<Map<String,Object>> resList = new ArrayList<>();
		for(TAbbBmliuyan bmliuyan:list){
			Map<String,Object> liuyanMap = new HashMap<>();
			liuyanMap.put("liuyan",bmliuyan);
			List<TAbbBmliuyan> huifuList = bmliuyanMapper.getHuifuList(bmliuyan.getId());
			liuyanMap.put("huifuList",huifuList);
			resList.add(liuyanMap);
		}
		return resList;
	}


	public List<TAbbBiammin> getMyBianminList(int page,String userid){
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("page",page);
		paramMap.put("userid",userid);
		List<TAbbBiammin> list = tAbbBiamminMapper.getMyBianminList(paramMap);
		return list;
	}


	/**
	 * 获得随机红包金额
	 * @param sum 红包剩余金额
	 * @param num 红包剩余个数
	 * @return
	 */
	private double getRedPcket(double price,double sum,int num){
		DecimalFormat df = new DecimalFormat("#.00");
		double avg = Double.parseDouble(df.format(price/50));
		double redPcket = 0d;
		if(num>1){
			//按照剩余红包每个都为0.01时红包需要剩下的金额
			double minleft = num*0.01;
			//扣除需要剩下的红包，本次可领红包的最大金额
			double maxRedPcket = sum-minleft;
			//本次可领红包的最小金额
			double minRedPcket = 0.01;
			//在区间中随机获得红包金额
			redPcket =  minRedPcket + Math.random() * maxRedPcket % (maxRedPcket - minRedPcket + 1);
		}else{
			redPcket = sum;
		}
		return redPcket;
	}

	public Map<String,Object> deleteBianmin(String bmid){
		Map<String,Object> resMap = new HashMap<>();
		int flag = tAbbBiamminMapper.deleteByPrimaryKey(bmid);
		if(flag>0){
			resMap.put("msg","删除成功");
		}else{
			resMap.put("msg","删除失败");
		}
		resMap.put("success",true);
		return resMap;
	}


}
